'''
Created on 2011-10-02

@author: Michalis Famelis
'''

import gtk
import tempfile
from backend.script import Script
from backend.mixer import Mixer
from backend.tune import ParseError
import backend

gtk.gdk.threads_init()

from lib import vlc

vlc_instance = vlc.Instance()

class SambaPlayer(object):
	
	def __init__(self, gui):
		self.gui = gui
		
		self.player = vlc_instance.media_player_new()
		
		tempfile.tempdir = backend.mainPath
		self.tuneScriptFile = tempfile.NamedTemporaryFile(suffix=".tune", delete="True")
		self.mediaFile = tempfile.NamedTemporaryFile(suffix=".wav", delete="True")
			
	def updateGeneratedMusic(self):
		self.tuneScriptFile.seek(0,0)
		self.tuneScriptFile.write(self.gui.sambaTune)
		self.tuneScriptFile.flush()
		try:
			tune = Script(self.tuneScriptFile.name)
			self.tuneScriptFile.flush()
			Mixer(tune.sequence).mix(self.mediaFile.name)
			self.mediaFile.flush()
			self.gui.tuneChanged = False
		except ParseError as pe:
			self.gui.setStatus("error in line %d: %s" % (pe.line_number, pe.error))
		except Exception as e: #FIXME: proper error reporting
			self.gui.setStatus(str(e))
			
	def play(self):
		self.updateGeneratedMusic()
		self.player.set_media(vlc_instance.media_new(self.mediaFile.name))
		self.player.play()
	
	def pause(self):
		self.player.pause()
		
	def stop(self):
		self.player.stop()
				
	def finalize(self):
		self.tuneScriptFile.close()
		self.mediaFile.close()
				

